import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css'
import { getToken } from './utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login'] // 路由白名单

router.beforeEach(async(to, from, next) => {
  // 加载进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  if (getToken()) {
    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next({ path: '/' })
      // 结束进度条
      NProgress.done()
    } else {
      console.log('store.state.user', store.state.user)
      if (store.state.user.menus.length > 1) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const {
            roles
          } = await store.dispatch('user/getInfo')
          const routeStatus = store.state.settings.routesRole
          if (routeStatus == 'reception') {
            // 基于角色生成可访问路由图
            const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          }
          if (routeStatus == 'all') {
            const menus = await store.dispatch('user/getMenus')
            const accessRoutes = await store.dispatch('permission/allRoutes', {
              menus
            })
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          }
        } catch (err) {
          await store.dispatch('user/resetToken')
          Message.error(err || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
